package cn.com.bluemoon.daps.standard.common.report;

import cn.com.bluemoon.daps.model.dto.ModelDto;
import cn.com.bluemoon.daps.model.dto.ModelTableDto;
import cn.com.bluemoon.daps.model.entity.DapDataModelTableField;
import cn.com.bluemoon.daps.standard.entity.DapAuditChinResult;
import cn.com.bluemoon.daps.standard.entity.DapAuditStandardResult;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * R 为结果
 * @author Jarod.Kong
 * @date 2020/9/27 10:25
 */
public abstract class AbstractReportFieldCheck<R> implements IReportCheck{
    /**
     * 获取字段结果数据
     */
    private List<R> result;

    /**
     * 字段对应的表的{@link DapAuditChinResult#getId()} || {@link DapAuditStandardResult#getId()}
     */
    private String auditReportPid;

    /**
     * 记录错误数量
     */
    private AtomicInteger markErrorFieldSize;

    @Override
    public boolean generate(ModelDto modelDto) {
        List<ModelTableDto> tableModelDtos = modelDto.getTableModelDtos();
        List<R> results = tableModelDtos.parallelStream()
                .flatMap(t -> t.getFields().stream())
                .map(reportCheckFunc(modelDto))
                .collect(Collectors.toList());
        setResult(results);
        return checkPass(this.result);
    }

    public String getAuditReportPid() {
        return auditReportPid;
    }

    public AbstractReportFieldCheck<R> setAuditReportPid(String auditReportPid) {
        this.auditReportPid = auditReportPid;
        return this;
    }


    public void setResult(List<R> result) {
        this.result = result;
    }

    public List<R> getResult() {
        if (result == null) {
            result = Lists.newArrayList();
        }
        return result;
    }

    public int getErrorFieldSize() {
        if (markErrorFieldSize == null) {
            markErrorFieldSize = new AtomicInteger(0);
        }
        return markErrorFieldSize.get();
    }

    public void incrError(){
        if (markErrorFieldSize == null) {
            markErrorFieldSize = new AtomicInteger(0);
        }
        markErrorFieldSize.incrementAndGet();
    }

    /**
     * @return 报告实现函数
     */
    public abstract Function<DapDataModelTableField, R> reportCheckFunc(ModelDto modelDto);

    /**
     * 基于结果定义是否未通过
     *
     * @param list
     * @return
     */
    public abstract boolean checkPass(List<R> list);
}
